var app = getApp();
var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var wxUtil = require('../../utils/wxUtil.js');
var MPage = require('../MPage.js');

Page(common.extendPage(MPage, {
    data: {
        dataLoaded: false,
        loading: false,
        moreLoading: false,
        currentTab: 0,
        orderList: [],
        page: 1,
        noMore: false,

        timerStrs: {}
    },

    onLoad(options) {
        var self = this;

        self._timerList = {};
        self._toTab(+options.ty || 0, function() {
            self.setData({
                timerStrs: {},
                dataLoaded: true
            });
        });
    },

    /**
     * 事件切换tab
     */
    _tabSwitch(evt) {
        var index = +evt.currentTarget.dataset.current;
        var formId = evt.detail.formId;

        this._toTab(index);
        common.submitForm(formId);
    },

    _toTab(index, cb) {
        this.setData({
            currentTab: index,
            orderList: [],
            page: 1,
            noMore: false,
        });
        cb && cb();
        this._getOrderList({
            ty: index - 1
        }, cb);
    },

    _getOrderList(params, cb) {
        var self = this;
        var ty = params.ty;
        var isMore = params.isMore;
        var page = self.data.page || 1;
        var url = '/openapi/CActivity/getMyGroupBuyList';

        if (isMore) {
            self.setData({
                moreLoading: true
            });
        } else {
            self.setData({
                loading: true
            });
        }
        ajax.G(url, {
            page: page,
            type: ty,
        }, function(data) {
            var list = data.result || [];
            var orderList = list.concat(self.data.orderList);
            var toData = {
                orderList,
                noMore: list.length == 0,
                page: self.data.page + 1,
            };

            toData[isMore ? 'moreLoading' : 'loading'] = false;
            self.setData(toData);

            var _timerList = self._timerList = self._timerList || {};

            if (page == 1) { //重置定时器
                _timerList = self._timerList = {};
                self._timerId && clearTimeout(self._timerId);
                self.setData({
                    timerStrs: {},
                });
            }
            list.forEach(function(item) {
                var id = item.group_buy_id;
                var {
                    group_buy_id: id,
                    type
                } = item;
                var sec = type == 0 ? item['order_info']['left_time'] : item['left_time'];

                if ((type == 0 || type == 1) && sec && sec > 0) {
                    _timerList[id] = sec;
                }
            });

            if (page == 1 && Object.keys(_timerList).length > 0) { //启动定时器
                self._timerDown();
            }
            cb && cb();
        });
    },

    /**
     * 加载更多
     */
    _loadMore() {
        if (this.data.moreLoading || this.data.loading || this.data.noMore) {
            return;
        }
        this._getOrderList({
            ty: this.data.currentTab,
            isMore: true
        });
    },

    /**
     * 定时器列表
     */
    _timerDown() {
        var _self = this;
        var timerStrs = _self.data.timerStrs;
        var isOver = false;
        var _timerList = _self._timerList;
        var _timerListKeys = Object.keys(_timerList);

        if (_timerListKeys.length == 0) {
            return;
        }
        _timerListKeys.some(function(key) {
            var sec = _timerList[key];

            timerStrs[key] = util.getTimeBySec(sec);

            if (sec == 0) {
                isOver = true;
                return true;
            }
            _timerList[key] = --sec;
        });

        if (isOver) {
            _self._toTab(_self.data.currentTab);
            _self._timerId && clearTimeout(_self._timerId);
            return;
        }
        _self.setData({
            timerStrs,
        });
        _self._timerId = setTimeout(() => {
            _self._timerDown();
        }, 1000);
    },

    /**
     * 未支付订单支付
     */
    _payOrder(evt) {
        var _self = this;
        var {
            orderId,
            groupId
        } = evt.target.dataset;

        ajax.P('/openapi/CActivity/doPayAgain', {
            orderId,
            openId: app.getOpenId(),
        }, function(data) {
            var wxPayParams = JSON.parse(data.result.wxPayParams);
            var _package = wxPayParams.package;
            var prepayArr = _package.split('=');

            common.submitPrepay(prepayArr[1]);

            wxPayParams.success = function() {
                wx.redirectTo({
                    url: '/pages/groupBuyInfo/index?groupBuyId=' + groupId
                });

                _self._toTab(1);
            }
            wxUtil.wxPay(wxPayParams);
        });
    },
}));